package com.linrung.sf.scheduler.zwwx.service;

import com.linrung.core.model.ResultData;
import com.linrung.sf.scheduler.zwwx.entity.ZwwxMessageEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Module 消息服务
 * @Author Linyubang
 * @Date 2023 11 24
 **/
@Service("ZwwxMessageSendService")
public class ZwwxMessageSendService {

    private static Logger logger = Logger.getLogger(ZwwxMessageSendService.class);

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public void genAppealNodeTodo() {
        String sql = "select t.id,a.title,t.nodename,t.reachtime,t.sendusername,t.senddeptname,u.userid,u.syncuserid from lr_sf_appeal_node t " +
                     " left join lr_sf_appeal a on t.appealid=a.id left join lr_sf_user_role u on t.acceptdeptid=u.deptid " +
                     " and t.acceptuserrole=u.rolekey where t.delstate='0' and t.handlestate in ('0','1') " +
                     " and ( t.acceptdeptscope<>'5' or " +
                     "      (t.acceptdeptscope='5' and exists (select 1 from lr_sf_appeal_node r where r.nodeid=t.acceprelnodeid and r.appealid=t.appealid and r.handleuserid=u.userid)) ) "+
                     " and not exists (select 1 from lr_sf_message m where m.bkeyid=t.id) order by t.sendtime desc";
        this.genNoDealMessage(sql,"1");
    }

    public void genBackAppealNodeTodo() {
        String sql = "select t.id,a.title,'不受理退回' as nodename,t.accepttime as reachtime,t.acceptusername as sendusername, " +
                     "   t.acceptdeptname as senddeptname,t2.id as userid,t2.syncuserid from lr_sf_appeal_node t  " +
                     "   left join lr_sf_appeal a on t.appealid=a.id  " +
                     "   left join lr_pf_user_org t1 on t.senddeptid=t1.org_id left join lr_pf_user t2 on t1.user_id=t2.id  " +
                     "   where t.delstate='0' and t.handlestate='3'  " +
                     "   and exists (select 1 from lr_pf_user_role r left join lr_pf_role r1 on r.role_id=r1.id  " +
                     "   where r1.role_key in ('ROLE_ZJGLY_MGR','ROLE_XZ_FD_ROLE','ROLE_XQ_FD_ROLE') and r.user_id=t2.id ) " +
                     "   and not exists (select 1 from lr_sf_message m where m.bkeyid=t.id and m.receiverid=t2.id) order by t.accepttime desc ";
        this.genNoDealMessage(sql,"2");
    }

    public void genWorkTaskTodo() {
        String sql = "select t.id,t0.taskname as title,'专项工作任务' as nodename,t.createtime as reachtime,t.createusername as sendusername," +
                     "   t.createdeptname as senddeptname,t2.id as userid,t2.syncuserid " +
                     "   from LR_SF_WORKTASK_DEAL t  " +
                     "       left join LR_SF_WORKTASK t0 on t.taskid=t0.id " +
                     "       left join lr_pf_user_org t1 on t.handledeptid=t1.org_id " +
                     "       left join lr_pf_user t2 on t1.user_id=t2.id " +
                     "       where t.handlestate='0' and t.createtime>sysdate-2 " +
                     "    and exists (select 1 from lr_pf_user_role r left join lr_pf_role r1 on r.role_id=r1.id  " +
                     "     where r1.role_key in ('ROLE_DEPT_ROLE','ROLE_GRID_ROLE','ROLE_ZJGLY_MGR','ROLE_CJGZZ_MGR') and r.user_id=t2.id )  " +
                     "    and not exists (select 1 from lr_sf_message m where m.bkeyid=t.id) order by t.createtime desc";
        this.genNoDealMessage(sql,"3");
    }

    public void genAnnounce() {
        String sql = "select t0.id,t.title,'消息通知' as nodename,t.SEND_TIME as reachtime,t.APPLY_SEND_NAME as sendusername," +
                "   t.APPLY_DEPT_NAME as senddeptname,t2.ID as userid,t2.syncuserid " +
                "   from LR_SF_ANNOUNCE t  " +
                "       left join LR_SF_ANNOUNCE_RECEIVE t0 on t.ID=t0.ANNOUNCE_ID " +
                "       left join lr_pf_user t2 on t0.RECEIVE_ID=t2.ID " +
                "       where t.IS_TEMP=0 and t0.IS_DEL=0" +
                "    and not exists (select 1 from lr_sf_message m where m.bkeyid=t0.id) order by t.SEND_TIME desc";
        this.genNoDealMessage(sql,"0");
    }

    public void genPreAppealTodo() {
        String sql = "select t.id,t.title,'预受理事件' as nodename,t.updatestatetime as reachtime,n.handleusername as sendusername," +
                "   n.handledeptname as senddeptname,t2.id as userid,t2.syncuserid " +
                "   from LR_SF_WX_APPEAL t  " +
                "       left join lr_sf_wx_appeal_pre_node n on t.id=n.appealid and t.updatestateid=n.updatestateid " +
                "       left join lr_pf_user_org t1 on t.currentdeptid=t1.org_id " +
                "       left join lr_pf_user t2 on t1.user_id=t2.id " +
                "       where t.state in('1','2','3') and t.updatestatetime>sysdate-2" +
                "    and exists (select 1 from lr_pf_user_role r left join lr_pf_role r1 on r.role_id=r1.id   " +
                "     where r1.role_key in ('ROLE_DEPT_ROLE','ROLE_GRID_ROLE','ROLE_ZJGLY_MGR','ROLE_CJGZZ_MGR') and r.user_id=t2.id )  " +
                "    and not exists (select 1 from lr_sf_message m where m.bkeyid=t.id) order by t.updatestatetime desc ";
        this.genNoDealMessage(sql,"5");
    }

    public void genNoDealMessage(String sql, String msgType) {
        List<ZwwxMessageEntity> list = new ArrayList<ZwwxMessageEntity>();
        //1、先生成待发送的消息
        SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
        while (rs.next()) {
            ZwwxMessageEntity entity = new ZwwxMessageEntity();
            entity.setMsgType(msgType);
            entity.setBusinessKeyId(rs.getString("id"));
            entity.setTitle(rs.getString("title"));
            entity.setSource(rs.getString("nodename"));
            entity.setRemindTime(rs.getTimestamp("reachtime"));
            String sendUserName = rs.getString("sendusername");
            if(StringUtils.isEmpty(sendUserName)){
                sendUserName = "系统";
            }
            entity.setSender(sendUserName);
            String sendDeptName = rs.getString("senddeptname");
            if(StringUtils.isEmpty(sendDeptName)){
                sendDeptName = "系统";
            }
            entity.setSenderDept(sendDeptName);
            entity.setReceiverId(rs.getString("userid"));
            entity.setReceiverSyncUserId(rs.getString("syncuserid"));
            list.add(entity);
        }
        String insert = "insert into lr_sf_message(id,msgtype,bkeyid,title,subtitle,sourceuser,sourcedept,reachtime,receiverid,receiversyncuserid,createtime) values(?,?,?,?,?,?,?,?,?,?,sysdate) ";
        for (ZwwxMessageEntity e : list) {
            this.jdbcTemplate.update(insert, new Object[]{UUID.randomUUID().toString(), e.getMsgType(), e.getBusinessKeyId(), e.getTitle(), e.getSource(),
                    e.getSender(), e.getSenderDept(), e.getRemindTime(), e.getReceiverId(), e.getReceiverSyncUserId()});
        }
        logger.info(String.format("本次要生成待发送消息(%s)总条数 = %d", msgType,list.size()));
        list.clear();
    }

    public List<ZwwxMessageEntity> loadNoDealMessageList(){
        List<ZwwxMessageEntity> list = new ArrayList<ZwwxMessageEntity>();
        //1、读取待发送消息
        String msgSql = "select a.* from lr_sf_message a where a.sendstate='0' and a.msgtype<>'9' and a.createtime>sysdate-2 order by a.createtime desc";
        SqlRowSet mr = this.jdbcTemplate.queryForRowSet(msgSql);
        while(mr.next()){
            ZwwxMessageEntity entity = new ZwwxMessageEntity();
            entity.setId(mr.getString("id"));
            entity.setBusinessKeyId(mr.getString("bkeyid"));
            entity.setTitle(mr.getString("title"));
            entity.setSource(mr.getString("subtitle"));
            entity.setRemindTime(mr.getTimestamp("reachtime"));
            entity.setSender(mr.getString("sourceuser"));
            entity.setSenderDept(mr.getString("sourcedept"));
            entity.setReceiverId(mr.getString("receiverid"));
            entity.setReceiverSyncUserId(mr.getString("receiversyncuserid"));
            entity.setCreateTime(new Date());
            entity.setMessageType(1);//卡片链接
            entity.setMsgType(mr.getString("msgtype"));
            list.add(entity);
        }
        return list;
    }

    public void updateReceiverWxSendStateById(String msgId,String state){
        String update = "update lr_sf_message set SENDSTATE=?,SENDTIME=sysdate where id=? ";
        this.jdbcTemplate.update(update,new Object[]{state,msgId});
    }

    /**
     * 发送短信
     * @param messageSendEntity
     * @param isNeedPrefixes
     * @param isNeedSuffixes
     */
    public ResultData addMessageSend(ZwwxMessageEntity messageSendEntity, String isNeedPrefixes, String isNeedSuffixes) {
        ResultData rs = new ResultData();
        rs.setState(1);
        return rs;
    }

    /**
     * 发送短信
     * @param messageSendEntity
     */
    public ResultData addMessageSend(ZwwxMessageEntity messageSendEntity) {
        return this.addMessageSend(messageSendEntity,null,null);
    }

}
